import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:top_foundation/utils/util.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:whale/helper/utils/httputils/net_api.dart';
import 'package:whale/pages/watch/model/Level_data.dart';
import 'package:whale/pages/watch/model/trend_point.dart';

import '../../means/main/widgets/selection/index.dart';
import '../model/type_data.dart';
import 'index.dart';

class WatchController extends GetxController
    with GetSingleTickerProviderStateMixin {
  WatchController();

  final state = WatchState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.titleTc = TabController(length: 3, vsync: this);
    state.titleTc.addListener(() {
      getData(state.titleTc.index);
    });
    state.selectionTitles = [
      SelectionModel(text: '地区', style: SelectionStyle.column, list: [
        SelectionModel(text: '全国', isShow: true, list: [
          SelectionModel(
            text: '全部',
            itemStyle: SelectionItemStyle.checkbox,
          )
        ]),
        SelectionModel(
            text: '安徽',
            itemStyle: SelectionItemStyle.checkbox,
            list: [
              SelectionModel(
                  text: '芜湖', itemStyle: SelectionItemStyle.checkbox),
            ])
      ]),
      SelectionModel(
          text: '领域',
          style: SelectionStyle.wrap,
          isMutiable: true,
          rowCount: 2,
          list: [
            '全部',
            '市场准入与退出',
            '招商引资',
            '招标投标',
          ]
              .asMap()
              .map((key, e) => MapEntry(
                    key,
                    SelectionModel(
                      text: e,
                      itemStyle: SelectionItemStyle.radio,
                      isMutiable: key != 0,
                      rowCount: 2,
                    ),
                  ))
              .values
              .toList()),
      SelectionModel(text: '更多筛选', style: SelectionStyle.column, list: [
        SelectionModel(
            title: '发布时间',
            text: '',
            isMutiable: false,
            style: SelectionStyle.wrap,
            rowCount: 3,
            tag: 1,
            relateTag: 2,
            list: ['全部', '本月', '本季度', '本年']
                .asMap()
                .map(
                  (key, value) => MapEntry(
                    key,
                    SelectionModel(
                      text: value,
                      rowCount: 3,
                      isSelected: value == '本月',
                      itemStyle: SelectionItemStyle.tag,
                    ),
                  ),
                )
                .values
                .toList()),
        SelectionModel(
          text: '',
          child: SizedBox(
            height: 10.r,
          ),
        ),
        SelectionModel(
            text: '', itemStyle: SelectionItemStyle.date, tag: 2, relateTag: 1),
        SelectionModel(
          text: '',
          child: SizedBox(
            height: 10.r,
          ),
        ),
        // SelectionModel(text: '', title: '多个关键词组合查询', list: [
        //   SelectionModel(
        //     text: '',
        //     itemStyle: SelectionItemStyle.input,
        //   )
        // ]),
        // SelectionModel(
        //   text: '',
        //   child: SizedBox(
        //     height: 10.r,
        //   ),
        // ),
        // SelectionModel(text: '', title: '发布机构', list: [
        //   SelectionModel(
        //     text: '',
        //     itemStyle: SelectionItemStyle.input,
        //   )
        // ]),
        // SelectionModel(
        //   text: '',
        //   child: SizedBox(
        //     height: 10.r,
        //   ),
        // ),
        // SelectionModel(
        //     title: '风险等级',
        //     text: '',
        //     isMutiable: true,
        //     style: SelectionStyle.wrap,
        //     rowCount: 3,
        //     list: ['全部', '高风险', '中风险', '低风险', '暂无风险']
        //         .asMap()
        //         .map(
        //           (key, value) => MapEntry(
        //             key,
        //             SelectionModel(
        //               text: value,
        //               isMutiable: key != 0,
        //               rowCount: 3,
        //               itemStyle: SelectionItemStyle.radio,
        //             ),
        //           ),
        //         )
        //         .values
        //         .toList()),
      ]),
    ];
    state.carouselData = [
      '河南省人民政府发布招标需求，评估为低风险',
      '北京市人民政府发布招标需求，评估为低风险',
      'XX市发布投标文件涉嫌违规，评估为高风险'
    ];

    state.webCtrl = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(
        onPageStarted: (url) {
          Get.log('onPageStarted$url');
        },
        onPageFinished: (url) {
          Get.log('onPageFinished$url');
        },
        onWebResourceError: (error) {
          Get.log(error.description);
        },
      ));
    getData(0);
    state.webCtrl.loadRequest(Uri.parse('http://192.168.19.135:8080/#/map'));
  }

  var reportTypes = ['全部', '政策措施', '招标采购'];
  var reportTypes2 = ['政策措施,招标采购', '政策措施', '招标采购'];

  getData(int index, {String? startTime, String? endTime}) {
    getTrendData(reportTypes[index], startTime: startTime, endTime: endTime);
    getIllDocSumByRiskLevel(reportTypes2[index],
        startTime: startTime, endTime: endTime);
    getIllDocByProblemType(reportTypes2[index],
        startTime: startTime, endTime: endTime);
  }

  void getTrendData(String reportType,
      {String? startTime, String? endTime}) async {
    var res = await WatchApi.trendData(reportType,
        startTime: startTime, endTime: endTime);
    if (res.isSuccess) {
      List list = res.data;
      List<TrendPoint> trendpoints =
          list.map((e) => TrendPoint.fromJson(e)).toList();
      for (var element in trendpoints) {
        state.trendGroupData.add({
          'date': element.dateStr ?? '',
          'name': '文件数',
          'points': element.docSum ?? 0
        });
        state.trendGroupData.add({
          'date': element.dateStr,
          'name': '疑似违规数',
          'points': element.illDocSum
        });
        state.trendGroupData.add({
          'date': element.dateStr,
          'name': '疑似高风险违规数',
          'points': element.illHighDocSum
        });
      }
      update();
    }
  }

  void getIllDocSumByRiskLevel(String reportType,
      {String? startTime, String? endTime}) async {
    var res = await WatchApi.getIllDocSumByRiskLevel(reportType,
        startTime: startTime, endTime: endTime);
    if (res.isSuccess) {
      List list = res.data;
      state.lievDatas = list.map((e) => LevelData.fromJson(e)).toList();

      update();
    }
  }

  void getIllDocByProblemType(String reportType,
      {String? startTime, String? endTime}) async {
    var res = await WatchApi.getIllDocByProblemType(reportType,
        startTime: startTime, endTime: endTime);
    if (res.isSuccess) {
      List list = res.data;
      state.typeDatas = list.map((e) => TypeData.fromJson(e)).toList();

      update();
    }
  }

  void selectionResults(SelectionResultModel res) {
    Get.log(res.toString());
    Map<String, String> args = {};

    if (res.key == '地区') {
      args['province'] = '';
      args['city'] = '';
      if (isZeroList(res.items)) {
        if (res.val == '全部') {
          args['province'] = '';
        } else {
          args['province'] = res.val ?? '';
        }
      } else {
        args['city'] = res.items!.map((e) => e.val ?? '').join(',');
      }
    } else if (res.key == '领域') {
      if (res.val == '全部') {
        args['industryType'] = '';
      } else {
        args['industryType'] = res.val ?? '';
      }
    } else if (res.key == '更多筛选') {
      args['startTime'] = '';
      args['endTime'] = '';
      args['riskLevel'] = '';

      res.items?.forEach((e2) {
        if (e2.key == '发布时间') {
          var dateVal = getDateVal(e2.val ?? '');

          state.startTime = dateVal.first;
          state.endTime = dateVal.last;

          getData(
            state.titleTc.index,
            startTime: state.startTime,
            endTime: state.endTime,
          );
        } else if (e2.key == '风险等级') {
          args['riskLevel'] = e2.val ?? '';
        } else if (e2.key == '发布机构') {
        } else if (e2.key == '多个关键词组合查询') {
        } else {}
      });
    }
  }

  List<String> getDateVal(String data) {
    List<String> list = [];
    if (data == '全部') {
      var start = '';
      var end = '';
      return [end, start];
    } else if (data == '本季度') {
      var quarters = getQuarters();
      var start = quarters.last;
      var end = quarters.first;

      return [end, start];
    } else if (data == '本月') {
      var now = DateTime.now();
      var start = DateFormat.format(now, DateFormatType.ymd);
      var end = DateFormat.format(
          now.add(const Duration(days: -30)), DateFormatType.ymd);
      return [end, start];
    } else if (data == '本年') {
      var now = DateTime.now();

      var start = DateFormat.format(now, DateFormatType.ymd);
      var end = DateFormat.format(DateTime(now.year, 1, 1), DateFormatType.ymd);
      return [end, start];
    } else {
      return data.split(',').toList();
    }
    return list;
  }

  List<String> getQuarters() {
    var now = DateTime.now();

    ///当前月份
    int _currentMonth = now.month;
    int year = now.year;
    int day = now.day;
    if (_currentMonth >= 1 && _currentMonth <= 3) {
      return ['$year-01-01', '$year-$_currentMonth-$day'];
    } else if (_currentMonth >= 4 && _currentMonth <= 6) {
      return ['$year-04-01', '$year-$_currentMonth-$day'];
    } else if (_currentMonth >= 7 && _currentMonth <= 9) {
      return ['$year-07-01', '$year-$_currentMonth-$day'];
    } else {
      return ['$year-10-01', '$year-$_currentMonth-$day'];
    }
  }

  String getEnd(String start, int add) {
    var starts = start.split('-');
    var end = (int.parse(starts[0]) - add).toInt().toString();
    starts[0] = end;

    return starts.join('-');
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
